//
//  EPMComposeViewController.m
//  WeiBoByOC
//
//  Created by 马继鵬 on 17/4/1.
//  Copyright © 2017年 7TH. All rights reserved.
//

#import "EPMComposeViewController.h"
#import "EPMTextView.h"
#import "EPMPictureView.h"
#import "EPMBottomBtnView.h"
#import "EPMEmotionKeyBoardView.h"
#import "EPMTextAttachment.h"

@interface EPMComposeViewController ()<UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak,nonatomic) UIButton* sendBtn;
@property (weak,nonatomic) EPMTextView* textView;
@property (weak,nonatomic) EPMPictureView* pictureView;
@property (weak,nonatomic) EPMBottomBtnView* bottomBtnView;
@property (strong,nonatomic) NSMutableArray<UIImage*>* imgList;
@property (strong,nonatomic) EPMEmotionKeyBoardView* emotionKeyBoardView;
@end

@implementation EPMComposeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupUI];
    
}
- (NSMutableArray<UIImage*>*)imgList{
    if (_imgList == nil){
        _imgList = [[NSMutableArray<UIImage*> alloc]init];
    }
    return _imgList;
}

- (void)setupUI{
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem EPM_Title:@"取消" imageName:nil target:self action:@selector(cancelBtnClick)];
    [self addSendBtn];
    [self addTitle];
    [self addTextView];
    [self addPictureView];
    [self addBottomBtnView];
    
#pragma
#pragma-通知监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChanged:) name:UIKeyboardDidChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(emotionBtnClicked:) name:EMOTIONBTNCLICKEDINFO object:nil];
    
    
}
#pragma
#pragma-表情按钮点击
- (void)emotionBtnClicked:(NSNotification*)noti{
    
    EPMEmotionModel* model = noti.object;
//    NSLog(@"%@",model);
    
    [[EPMEmotionTool sheard] saveRecentEmotions:model];
    //刷新最近表情视图
    [self.emotionKeyBoardView reloadRecntEmotions];
    
    if (model.isEmoji){
        [self.textView insertText:[model.code emoji]];
    }else{
        
        NSMutableAttributedString* allAttr = [[NSMutableAttributedString alloc]initWithAttributedString:self.textView.attributedText];
        
        
        
        NSString* allPath = model.allPath;
        UIImage* img = [UIImage imageNamed:allPath inBundle:[EPMEmotionTool sheard].emotionBundle compatibleWithTraitCollection:nil];
        CGFloat lineHight = self.textView.font.lineHeight;
        
        //设置富文本
        EPMTextAttachment* attachment = [[EPMTextAttachment alloc]init];
        attachment.emotionModel = model;
        attachment.image = img;
        attachment.bounds = CGRectMake(0, -4, lineHight, lineHight);
        NSAttributedString* tempAttr = [NSAttributedString attributedStringWithAttachment:attachment];
        
        //拼接替换
        NSRange selectRange = self.textView.selectedRange;
        [allAttr replaceCharactersInRange:selectRange withAttributedString:tempAttr];
        [allAttr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0,allAttr.length)];

//
//        NSParagraphStyle* paragraphStyle = [NSParagraphStyle defaultParagraphStyle];
//        
//        
//        [allAttr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, allAttr.length)];
        //赋值
        self.textView.attributedText = [allAttr copy];
    
        
        //光标复位
        self.textView.selectedRange = NSMakeRange(selectRange.location+1, 0);
        
        //代理系统发送监听信息
        [[NSNotificationCenter defaultCenter]postNotificationName:UITextViewTextDidChangeNotification object:nil];
        //启动代理事件
        [self.textView.delegate textViewDidChange:self.textView];
    }
    
    
}





#pragma
#pragma-键盘监听
- (void)keyboardFrameChanged:(NSNotification*)noti{
    CGRect frame = [noti.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    [self.bottomBtnView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(frame.origin.y - screenHeight);
    }];
    //动画设置
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
    
    
}

- (void)addTitle{
    UILabel* label = [[UILabel alloc]init];
    NSString* name = [EPMUserAccountModelView sheardTool].account.name;
    NSString* text = [NSString stringWithFormat:@"发微博\n %@",name];
    NSRange range = [text rangeOfString:name];
    NSMutableAttributedString* atrr = [[NSMutableAttributedString alloc]initWithString:text];
    [atrr addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12],NSForegroundColorAttributeName:THEMECOLOR} range:range];
    label.numberOfLines = 2;
    label.attributedText = atrr;
    label.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = label;
}


- (void)addSendBtn{
    
    UIButton* sendBtn = [[UIButton alloc]init];
    _sendBtn = sendBtn;
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [sendBtn setBackgroundImage:[UIImage imageNamed:@"common_button_orange"] forState:UIControlStateNormal];
    [sendBtn setBackgroundImage:[UIImage imageNamed:@"common_button_orange_highlighted"] forState:UIControlStateHighlighted];
    [sendBtn setBackgroundImage:[UIImage imageNamed:@"common_button_white_disable"] forState:UIControlStateDisabled];
    [sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sendBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateDisabled];
    [sendBtn addTarget:self action:@selector(uploadMessage) forControlEvents:UIControlEventTouchUpInside];
    sendBtn.titleLabel.font = [UIFont systemFontOfSize:FONTSIZENORMAL];
    sendBtn.frame = CGRectMake(0, 0, 40, 30);
   
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:sendBtn];
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
}

- (void)addTextView{
    EPMTextView* textView = [[EPMTextView alloc]init];
    self.textView = textView;
    [self.view addSubview:textView];
    textView.font = [UIFont systemFontOfSize:FONTSIZENORMAL];
    textView.textColor = [UIColor darkGrayColor];
    textView.delegate = self;
    textView.alwaysBounceVertical = YES;
    [textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.top.equalTo(self.view);
    }];
    
}

- (void)addPictureView{
    
    EPMPictureView* pictureView = [[EPMPictureView alloc]init];
    _pictureView = pictureView;
//    pictureView.hidden = YES;
    pictureView.backgroundColor = [UIColor lightGrayColor];
    [self.textView addSubview:pictureView];
    [pictureView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.textView).offset(100);
        make.centerX.equalTo(self.textView);
        make.width.height.mas_equalTo(screenWidth-20);
    }];
    pictureView.addPictureBlock= ^(){
        [self getPicture];
    };
    
}
- (void)addBottomBtnView{
    EPMBottomBtnView* bottomBtnView = [[EPMBottomBtnView alloc]init];
    _bottomBtnView = bottomBtnView;
    [self.view addSubview:bottomBtnView];
    
    [bottomBtnView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.bottom.trailing.equalTo(self.view);
        make.height.mas_equalTo(40);
    }];
    
    bottomBtnView.btnClickBlock = ^(ComposeBtnType type){
        switch (type) {
            case 1001:
//                NSLog(@"添加图片");
                [self getPicture];
                break;
            case 1002:
                
                break;
            case 1003:
                
                break;
            case 1004:
//                NSLog(@"添加表情");
                [self switchKeyBoard];
                break;
            case 1005:
                
                break;
            default:
                break;
        }
        
        
        
    };
    
}

- (EPMEmotionKeyBoardView*)emotionKeyBoardView{
    if (_emotionKeyBoardView == nil){
        _emotionKeyBoardView =[[EPMEmotionKeyBoardView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 216)];
    }
    
    return _emotionKeyBoardView;
}

#pragma
#pragma-键盘切换
- (void)switchKeyBoard{
    
   
    if(self.textView.inputView == nil){
        self.textView.inputView = self.emotionKeyBoardView;
        self.bottomBtnView.emotionBtnName = @"compose_keyboardbutton_background";
    }else{
        self.textView.inputView = nil;
        self.bottomBtnView.emotionBtnName = @"compose_emoticonbutton_background";
    }
    [self.textView reloadInputViews];
    [self.textView becomeFirstResponder];
}

#pragma
#pragma-图片展示代理方法
- (void)getPicture{
    UIImagePickerController* controller = [[UIImagePickerController alloc]init];
    controller.delegate = self;
    [self presentViewController:controller animated:YES completion:nil];
}
#pragma
#pragma-imgPickerVC的代理方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage* img = info[@"UIImagePickerControllerOriginalImage"];
    UIImage* scaleImg = [img getScaleImageWithMaxWidth:400];
    [self.imgList addObject:scaleImg];
    
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    self.pictureView.imgList = _imgList;
}



//textView代理方法
- (void)textViewDidChange:(UITextView *)textView{
    self.sendBtn.enabled = self.textView.hasText;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.textView resignFirstResponder];
}

#pragma
#pragma-点击事件
- (void)cancelBtnClick{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma
#pragma-处理textView中的富文本内容
- (NSString*)dealWithTextViewAttrabute{
    
    
    NSMutableString* text = [NSMutableString new];
    [self.textView.attributedText enumerateAttributesInRange:NSMakeRange(0, self.textView.attributedText.length) options:0 usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
        if ( attrs[@"NSAttachment"] != nil){
            EPMTextAttachment* attachment = attrs[@"NSAttachment"];
            [text appendString:attachment.emotionModel.chs];
        }else{
            NSString* str = [self.textView.attributedText attributedSubstringFromRange:range].string;
            [text appendString: str];
        }
    }];
    return  text;
}



- (void)uploadMessage{
    
    NSString* text = [self dealWithTextViewAttrabute];
    
    if (self.pictureView.imgList.count >=1){
        [self sendMessage:text pictures:self.pictureView.imgList finished:^(id res, NSError *error) {
            if (error != nil){
                [SVProgressHUD  showErrorWithStatus:@"上传失败"];
            }else{
                [SVProgressHUD showSuccessWithStatus:@"上传成功"];
            }
            //上传结束后退出
            [self cancelBtnClick];
        }];
    }else{
        [self sendMessagesendMessageWithMessage:text finished:^(id res, NSError *error) {
            if (error != nil){
                [SVProgressHUD  showErrorWithStatus:@"上传失败"];
            }else{
                [SVProgressHUD showSuccessWithStatus:@"上传成功"];
            }
            //上传结束后退出
            [self cancelBtnClick];
        }];
    }
    
    
    
}


- (void) sendMessagesendMessageWithMessage:(NSString*) text finished:(void(^)(id res, NSError *error)) finishBlock
{
    [[EPMNetWorkTool sheardTool] sendMessageWithMessage:text finished:finishBlock];
}

- (void)sendMessage:(NSString*) text pictures:(NSArray*)pictures finished:(void(^)(id res, NSError *error)) finishBlock
{
    [[EPMNetWorkTool sheardTool] sendMessageWithMessage:text pictures:pictures finished:finishBlock];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


@end
